package com.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.product.enmu.DeletedEnum;
import com.product.enmu.OperatorType;
import com.product.entity.DefectLog;
import com.product.mapper.DefectLogMapper;
import com.product.service.IDefectLogService;
import com.product.service.IOperationLogService;
import com.product.utils.PageUtils;
import com.product.vo.DefectLogVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DefectLogServiceImpl extends ServiceImpl<DefectLogMapper, DefectLog> implements IDefectLogService {
    @Autowired
    private IOperationLogService operatorService;

    @Override
    public PageUtils getAllDefectLog(Integer size, Integer current, Integer lineId, Integer orderItemId, Integer timeOrderBy) {
        Page<DefectLog> defectLogPage = new Page<>(current, size);
        LambdaQueryWrapper<DefectLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(lineId != null, DefectLog::getLineId, lineId);
        queryWrapper.eq(orderItemId != null, DefectLog::getOrderItemId, orderItemId);
        queryWrapper.orderBy(timeOrderBy != null, timeOrderBy != null && timeOrderBy == 0, DefectLog::getCreationTime);

        Page<DefectLog> page = this.baseMapper.selectPage(defectLogPage, queryWrapper);

        List<DefectLogVo> defectLogVoList = page.getRecords().stream().map(item -> {
            DefectLogVo defectLogVo = new DefectLogVo();
            BeanUtils.copyProperties(item, defectLogVo);
            return defectLogVo;
        }).toList();
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(defectLogVoList);
        return pageUtils;
    }

    @Override
    public void deleteDefectLog(Integer defectLogId) {
        LambdaUpdateWrapper<DefectLog> updateWrapper = new LambdaUpdateWrapper<DefectLog>()
                .eq(DefectLog::getDefectLogId, defectLogId)
                .set(DefectLog::getDeleted, DeletedEnum.DELETE.getValue());
        this.baseMapper.update(updateWrapper);

        operatorService.addOperation(OperatorType.Delete.getCode(), "删除DefectLog表");
    }

    @Override
    public void deleteDefectLogs(List<Integer> defectLogIds) {
        for (Integer defectLogId : defectLogIds) {
            deleteDefectLog(defectLogId);
        }
    }
}
